package com.xuebusi.toutiao.admin.api.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuebusi.toutiao.admin.api.article.dao.ArticleDao;
import com.xuebusi.toutiao.admin.api.article.entity.ArticleEntity;
import com.xuebusi.toutiao.admin.api.article.service.ArticleService;
import com.xuebusi.toutiao.admin.api.article.vo.*;
import com.xuebusi.toutiao.admin.api.common.config.GlobalConfig;
import com.xuebusi.toutiao.admin.api.common.exception.CustomException;
import com.xuebusi.toutiao.admin.api.common.result.ApiResult;
import com.xuebusi.toutiao.admin.api.common.result.PageInfo;
import com.xuebusi.toutiao.admin.api.common.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 文章服务实现类
 */
@Slf4j
@Service("articleService")
public class ArticleServiceImpl extends ServiceImpl<ArticleDao, ArticleEntity> implements ArticleService {
    @Resource
    private GlobalConfig globalConfig;

    @Resource
    private FileUtil fileUtil;

    /**
     * 创建文章
     *
     * @param userId    用户id
     * @param draft     是否草稿
     * @param createPVO 文章表单
     * @return
     */
    @Override
    public ResponseEntity<ApiResult<ArticleCreateRVO>> createArticle(
            Integer userId, Boolean draft, ArticleCreatePVO createPVO) {
        ArticleEntity articleEntity = new ArticleEntity();
        articleEntity.setUser_id(userId);
        articleEntity.setChannel_id(createPVO.getChannel_id());
        articleEntity.setResponse_type(null);
        articleEntity.setTitle(createPVO.getTitle());
        articleEntity.setContent(createPVO.getContent());
        articleEntity.setStatus(draft ? 0 : 1);
        Date now = new Date();
        articleEntity.setPubdate(now);
        articleEntity.setUpdate_time(now);

        // 封面处理
        articleEntity.setCover_type(createPVO.getCover().getType());
        List<String> images = createPVO.getCover().getImages();
        for (int i = 0; i < images.size(); i++) {
            images.set(i, fileUtil.getRelativeImagePath(images.get(i)));
        }
        articleEntity.setCover_images(StringUtils.join(images, ","));

        // 保存
        this.save(articleEntity);
        ArticleCreateRVO createRVO = new ArticleCreateRVO(articleEntity.getId());
        return new ResponseEntity<>(ApiResult.ok(createRVO), HttpStatus.CREATED);
    }

    /**
     * 修改文章
     *
     * @param userId    用户id
     * @param articleId 文章id
     * @param draft     是否草稿
     * @param updatePVO 修改表单
     * @return
     */
    @Override
    public ResponseEntity<ApiResult<ArticleCreateRVO>> updateArticle(
            Integer userId, Integer articleId, Boolean draft, ArticleUpdatePVO updatePVO) {
        ArticleEntity articleEntity = new ArticleEntity();
        articleEntity.setId(articleId);
        articleEntity.setChannel_id(updatePVO.getChannel_id());
        articleEntity.setResponse_type(null);
        articleEntity.setUser_id(userId);
        articleEntity.setTitle(updatePVO.getTitle());
        articleEntity.setContent(updatePVO.getContent());
        articleEntity.setStatus(draft ? 0 : 1);
        if (articleId == null) {
            articleEntity.setPubdate(new Date());
        }
        articleEntity.setUpdate_time(new Date());

        // 封面处理
        articleEntity.setCover_type(updatePVO.getCover().getType());
        List<String> images = updatePVO.getCover().getImages();
        for (int i = 0; i < images.size(); i++) {
            images.set(i, fileUtil.getRelativeImagePath(images.get(i)));
        }
        articleEntity.setCover_images(StringUtils.join(images, ","));

        // 更新
        this.updateById(articleEntity);
        ArticleCreateRVO createRVO = new ArticleCreateRVO(articleEntity.getId());
        return new ResponseEntity<>(ApiResult.ok(createRVO), HttpStatus.CREATED);
    }

    /**
     * 获取文章详情
     *
     * @param articleId 文章id
     * @return
     */
    @Override
    public ResponseEntity<ApiResult<ArticleDetailVO>> getArticle(Integer articleId) {
        ArticleEntity articleEntity = this.getById(articleId);
        if (articleEntity == null) {
            throw new CustomException("文章不存在", 401);
        }
        ArticleDetailVO detailVO = new ArticleDetailVO();
        detailVO.setId(articleEntity.getId());
        detailVO.setTitle(articleEntity.getTitle());
        detailVO.setContent(articleEntity.getContent());
        detailVO.setChannel_id(articleEntity.getChannel_id());
        // 文章封面图片处理
        ArticleCover cover = new ArticleCover();
        cover.setType(articleEntity.getCover_type());
        String[] images = articleEntity.getCover_images().split(",");
        for (int i = 0; i < images.length; i++) {
            images[i] = globalConfig.getWebSite() + images[i];
        }
        cover.setImages(Arrays.asList(images));
        detailVO.setCover(cover);
        return ResponseEntity.ok(ApiResult.ok(detailVO));
    }

    /**
     * 分页查询文章列表
     *
     * @param queryPVO 查询条件
     * @return
     */
    @Override
    public ResponseEntity<ApiResult<PageInfo<ArticlePageRVO>>> pageList(ArticleQueryPVO queryPVO) {
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPage(queryPVO.getPage());
        pageInfo.setPer_page(queryPVO.getPer_page());

        Page<ArticleEntity> page = new Page<>(queryPVO.getPage(), queryPVO.getPer_page());
        QueryWrapper<ArticleEntity> queryWrapper = new QueryWrapper<>();
        if (queryPVO.getResponse_type() != null) {
            queryWrapper.eq("response_type", queryPVO.getResponse_type());
        }
        if (queryPVO.getStatus() != null) {
            queryWrapper.eq("status", queryPVO.getStatus());
        }
        if (queryPVO.getChannel_id() != null) {
            queryWrapper.eq("channel_id", queryPVO.getChannel_id());
        }
        if (queryPVO.getBegin_pubdate() != null) {
            queryWrapper.ge("pubdate", queryPVO.getBegin_pubdate());
        }
        if (queryPVO.getEnd_pubdate() != null) {
            queryWrapper.le("pubdate", queryPVO.getEnd_pubdate());
        }
        Page<ArticleEntity> pageResult = this.page(page, queryWrapper);
        pageInfo.setTotal_count(pageResult.getTotal());

        List<ArticleEntity> entityList = pageResult.getRecords();
        List<ArticlePageRVO> rvoList = new ArrayList<>();
        for (ArticleEntity entity : entityList) {
            ArticlePageRVO rvo = new ArticlePageRVO();
            BeanUtils.copyProperties(entity, rvo);
            ArticleCover cover = new ArticleCover();
            cover.setType(entity.getCover_type());
            String[] images = entity.getCover_images().split(",");
            for (int i = 0; i < images.length; i++) {
                images[i] = globalConfig.getWebSite() + images[i];
            }
            cover.setImages(Arrays.asList(images));
            rvo.setCover(cover);
            rvoList.add(rvo);
        }

        pageInfo.setResults(rvoList);
        return ResponseEntity.ok(ApiResult.ok(pageInfo));
    }

    /**
     * 删除文章
     *
     * @param userId    用户id
     * @param articleId 文章id
     * @return
     */
    @Override
    public ResponseEntity delete(Integer userId, Integer articleId) {
        log.info(">>> delete article, userId:{}, articleId:{}", userId, articleId);
        this.removeById(articleId);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    /**
     * 文章搜索
     *
     * @param searchPVO 搜索参数
     * @return
     */
    @Override
    public ResponseEntity<ApiResult<PageInfo<ArticleSearchRVO>>> search(ArticleSearchPVO searchPVO) {
        Page<ArticleEntity> page = new Page<>(searchPVO.getPage(), searchPVO.getPer_page());
        Page<ArticleEntity> pageResult = this.page(page,
                new QueryWrapper<ArticleEntity>().like("title", searchPVO.getQ()));
        List<ArticleSearchRVO> rvoList = new ArrayList<>();
        for (ArticleEntity record : pageResult.getRecords()) {
            ArticleSearchRVO searchRVO = new ArticleSearchRVO();
            searchRVO.setId(record.getId());
            searchRVO.setTitle(record.getTitle());
            searchRVO.setStatus(record.getStatus());
            searchRVO.setPubdate(record.getPubdate());
            // 文章封面
            ArticleCover cover = new ArticleCover();
            cover.setType(record.getCover_type());
            String[] images = record.getCover_images().split(",");
            cover.setImages(Arrays.asList(images));
            searchRVO.setCover(cover);
            // 添加到集合
            rvoList.add(searchRVO);
        }
        PageInfo pageInfo = new PageInfo();
        pageInfo.setTotal_count(pageResult.getTotal());
        pageInfo.setPage(searchPVO.getPage());
        pageInfo.setPer_page(searchPVO.getPer_page());
        pageInfo.setResults(rvoList);
        return ResponseEntity.ok(ApiResult.ok(pageInfo));
    }

    /**
     * 修改文章评论状态
     *
     * @param article_id    文章id
     * @param allow_comment 是否允许评论
     * @return
     */
    @Override
    public ResponseEntity<ApiResult<ArtCommentStatusRVO>> updateCommentStatus(Integer article_id, Boolean allow_comment) {
        ArticleEntity articleEntity = new ArticleEntity();
        articleEntity.setId(article_id);
        articleEntity.setComment_status(allow_comment);

        // 修改
        this.updateById(articleEntity);

        // 返回结果
        ArtCommentStatusRVO statusRVO = new ArtCommentStatusRVO();
        statusRVO.setArticle_id(article_id);
        statusRVO.setAllow_comment(allow_comment);
        return ResponseEntity.ok(ApiResult.ok(statusRVO));
    }
}
